using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace MyWebPagesStarterKit.Providers
{
    /// <summary>
    /// Enables a VisibleInMenu attribute to menuitems
    /// If attribute VisibleInMenu="false" is set, this menuitem is hidden in menu, but enable us to link to it.
    /// </summary>
    public class CustomSiteMapDataSource : SiteMapDataSource
    {
        public CustomSiteMapDataSource() { }

        protected override HierarchicalDataSourceView GetHierarchicalView(string viewPath)
        {
            SiteMapNode root = Provider.RootNode;
            SiteMapNode newRoot = root.Clone();

            SiteMapNodeCollection col = new SiteMapNodeCollection();

            foreach (SiteMapNode node in root.ChildNodes)
                col.AddRange(RecursiveNodesCheck(node));

            root = null;
            return new SiteMapHierarchicalDataSourceView(col);
        }

        private SiteMapNodeCollection RecursiveNodesCheck(SiteMapNode Node)
        {
            if (Node.ChildNodes.Count == 0)
            {
                if (Node["VisibleInMenu"] == null)
                    return (new SiteMapNodeCollection(Node));
                if (Node["VisibleInMenu"] == "True" || Roles.IsUserInRole("Administrators"))
                    return (new SiteMapNodeCollection(Node));
                else
                    return (new SiteMapNodeCollection());
            }
            SiteMapNodeCollection OutputCollection = new SiteMapNodeCollection();
            SiteMapNode NewNode = Node.Clone();
            SiteMapNodeCollection ChildrenCollection = new SiteMapNodeCollection();
            foreach (SiteMapNode ChildNode in Node.ChildNodes)
                ChildrenCollection.AddRange(RecursiveNodesCheck(ChildNode));
            NewNode.ChildNodes = ChildrenCollection;
            OutputCollection.Add(NewNode);
            return (OutputCollection);
        }
    }
}






